package com.zqq.goods.ui.fragment

import android.annotation.SuppressLint
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.util.EventLog
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.alibaba.android.arouter.launcher.ARouter
import com.eightbitlab.rxbus.Bus
import com.eightbitlab.rxbus.registerInBus
import com.kennyc.view.MultiStateView
import com.zqq.baselibrary.ext.onClick
import com.zqq.baselibrary.ext.setVisible
import com.zqq.baselibrary.ext.startLoading
import com.zqq.baselibrary.ui.fragment.BaseMvpFragment
import com.zqq.baselibrary.utils.AppPrefsUtils
import com.zqq.baselibrary.utils.YuanFenConverter
import com.zqq.goods.R
import com.zqq.goods.event.CartAllCheckedEvent
import com.zqq.goods.event.UpdateCartSizeEvent
import com.zqq.goods.event.UpdateTotalPriceEvent
import com.zqq.goods.injection.component.DaggerCartComponent
import com.zqq.goods.injection.module.CartModule
import com.zqq.goods.presenter.CartListPresenter
import com.zqq.goods.presenter.view.CartListView
import com.zqq.goods.service.bean.CartGoods
import com.zqq.goods.ui.adapter.CartGoodsAdapter
import com.zqq.provider.common.ProviderConstant
import com.zqq.provider.router.RouterPath
import kotlinx.android.synthetic.main.fragment_cart.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.jetbrains.anko.support.v4.toast

/**
 * 三、 购物车 Fragment
 * wc   （注意此不仅在MainActivity里，而且还在@link{CartActivity} 里承载）
 * @author zqq on 2018/8/5.
 */
class CartFragment : BaseMvpFragment<CartListPresenter>(), CartListView {

    private lateinit var mAdapter: CartGoodsAdapter
    private var mTotalPrice: Long = 0

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        super.onCreateView(inflater, container, savedInstanceState)
        return inflater.inflate(R.layout.fragment_cart, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
        initObserve()
    }

    override fun injectComponent() {
        DaggerCartComponent.builder()
                .activityComponent(mActivityComponent)
                .cartModule(CartModule())
                .build()
                .inject(this)
        mPresenter.mView = this
    }

    //加载数据
    override fun onStart() {
        super.onStart()
        loadData()
    }

    //初始化视图和事件
    private fun initView() {
        mCartGoodsRv.layoutManager = LinearLayoutManager(context)
        mAdapter = CartGoodsAdapter(context!!)
        mCartGoodsRv.adapter = mAdapter

        //编辑
        mHeaderBar.getRightView().onClick {
            refreshEditStatus()
        }

        //全选按钮事件
        mAllCheckedCb.onClick {
            for (item: CartGoods in mAdapter.dataList) {
                item.isSelected = mAllCheckedCb.isChecked
            }
            mAdapter.notifyDataSetChanged()
            //更新网络价格
            updateTotalPrice()
        }

        //删除按钮事件
        mDeleteBtn.onClick {
            val cartIdlist: MutableList<Int> = arrayListOf()
            //拿出被选中的
            mAdapter.dataList.filter { it.isSelected }
                    //获取被选中数据里的id，并放在cartIdlist里
                    .mapTo(cartIdlist) { it.id }

            if (cartIdlist.size == 0) {
                toast("请选择需要删除的数据")
            } else {
                mPresenter.deleteCartList(cartIdlist)
            }
        }

        //结算按钮事件
        mSettleAccountsBtn.onClick {
            val cartGoodsList: MutableList<CartGoods> = arrayListOf()
            //过滤所选择的
            mAdapter.dataList.filter { it.isSelected }
                    //it就是dataList的本身，所以可以返回
                    .mapTo(cartGoodsList) { it }

            if (cartGoodsList.size == 0) {
                toast("请选择需要提交的数据")
            } else {
                mPresenter.submitCart(cartGoodsList, mTotalPrice)
            }
        }
    }

    //加载数据
    private fun loadData() {
        mMultiStateView.startLoading()
        mPresenter.getCartList()
    }

    //注册监听
    private fun initObserve() {
        EventBus.getDefault().register(this)

        //全选 与 反选
        Bus.observe<CartAllCheckedEvent>().subscribe { t ->
            run {
                mAllCheckedCb.isChecked = t.isAllChecked
                updateTotalPrice()
            }
        }.registerInBus(this)

        //价格变化
        Bus.observe<UpdateTotalPriceEvent>().subscribe {
            updateTotalPrice()
        }.registerInBus(this)
    }

    //EventBus接收消息
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun CartAllCheckedEvent(event: CartAllCheckedEvent) {
        mAllCheckedCb.isChecked = event.isAllChecked
        updateTotalPrice()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun UpdateTotalPriceEvent(event: UpdateTotalPriceEvent) {
        updateTotalPrice()
    }

    /**
     * 更新总价
     */
    @SuppressLint("SetTextI18n")
    private fun updateTotalPrice() {
        mTotalPrice = mAdapter.dataList.filter { it.isSelected }
                .map { it.goodsCount * it.goodsPrice }
                .sum()

        mTotalPriceTv.text = "合计：${YuanFenConverter.changeF2YWithUnit(mTotalPrice)}"
    }

    /**
     * 刷新是否为编辑状态
     */
    private fun refreshEditStatus() {
        val isEditStatus = getString(R.string.common_edit) == mHeaderBar.getRightText()
        mTotalPriceTv.setVisible(isEditStatus.not())
        mSettleAccountsBtn.setVisible(isEditStatus.not())
        mDeleteBtn.setVisible(isEditStatus)

        mHeaderBar.getRightView().text = if (isEditStatus) {
            getString(R.string.common_complete)
        } else {
            getString(R.string.common_edit)
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        Bus.unregister(this)
        EventBus.getDefault().unregister(this)
    }


    /*---------------------接口返回----------------------*/
    //获取购物车列表回调
    override fun onGetCartListResult(result: MutableList<CartGoods>?) {
        if (result != null && result.size > 0) {
            mAdapter.setData(result)

            //修改-完成/编辑-是否显示
            mHeaderBar.getRightView().visibility = View.VISIBLE
//            mHeaderBar.getRightView().setVisible(true)

            //修改-界面切换-全选是否选中
            mAllCheckedCb.isChecked = false

            mMultiStateView.viewState = MultiStateView.VIEW_STATE_CONTENT
        } else {
            mHeaderBar.getRightView().setVisible(false)
            mMultiStateView.viewState = MultiStateView.VIEW_STATE_EMPTY
        }

        //本地存储并发送事件刷新UI
        AppPrefsUtils.putInt(RouterPath.GoodsCenter.SP_CART_SIZE, result?.size ?: 0)
        Bus.send(UpdateCartSizeEvent())
//        EventBus.getDefault().post(UpdateCartSizeEvent())

        //更新总价
        updateTotalPrice()
    }

    //提交购物车回调
    override fun onSubmitCartListResult(result: Int) {
        //注意这里时整型，不能显示，要改为字符串
//        toast(result)  //"$result"
        toast("$result")  //"$result"

        ARouter.getInstance().build(RouterPath.OrderCenter.PATH_ORDER_CONFIRM)
                .withInt(ProviderConstant.KEY_ORDER_ID, result)
                .navigation()
    }

    //删除购物车回调
    override fun onDeleteCartResult(result: Boolean) {
        toast("删除成功")
        refreshEditStatus()
        loadData()
    }


    //Activity里调用(设置Back是否可见)
    fun setBackVisible(isVisible: Boolean) {
        mHeaderBar.getLeftView().setVisible(isVisible)
    }

}